<?php
namespace app\common\business;
use app\common\model\mysql\Category;
use think\Exception;

class CategoryBus{
    public $categoryObj = null;
    public function __construct()
    {
        $this->categoryObj = new Category();
    }

    /* 分类添加
     * @param $data
     */
    public function add($data){
        //是否存在
        $categoryName = $data['category_name'];
        $id = $this->categoryObj->where('category_name',$categoryName)->value('id');
        if($id){
            throw new Exception('该分类名称已存在');
        }
        try{
            $this->categoryObj->save($data);
        }catch (\Exception $e){
             throw new Exception('服务器内容异常');
        }
        return $this->categoryObj->id;
    }

    /*
     * 获取递归数据
     */
    public function getNormalCategorys(){
       $field = "id,category_name,parent_id";
       $category =  $this->categoryObj->getNormalData($field);
       if(!$category){
           $category = [];
       }else{
           $category =  $category->toArray();
       }
       return $category;
    }

    /*
     * 获取列表数据
     */
    public function getList($where,$pageNum){
       $list = $this->categoryObj->getLists($where,$pageNum);
       if(!$list){
          return [];
       }
       $result = $list->toArray();
       $result['rendor'] = $list->render();
       return $result;
    }

    /*
     *排序
     */
    public function listOrder($id,$listSort){
         $res= $this->getDataById($id);
         if(!$res){
             throw new Exception('不存在该记录');
         }
         $data['sort'] = $listSort;
         try{
            $res = $this->categoryObj->updateBySort($id,$data);
         }catch (\Exception $e){
             return false;
         }
         return $res;
    }

   /*
    * 修改状态
    */
   public function status($id,$status){
       $res= $this->getDataById($id);
       if(!$res){
           throw new Exception('不存在该记录');
       }
       $data['status'] = $status;
       try{
           $res = $this->categoryObj->updateBySort($id,$data);
       }catch (\Exception $e){
           return false;
       }
       return $res;
   }

    /*
     * 通过id获取数据
     */
    public function getDataById($id){
        $result= $this->categoryObj->find($id);
        if(empty($result)){
            return [];
        }
        $result = $result->toArray();
        return $result;
    }

}